namespace SimpleWebServices.Web.UI.Html
{
    using System;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;

    [XmlRoot("element")]
    public abstract class InnerElements : Element, IInnerElements, IXmlSerializable
    {
        private ElementCollection _elements;

        protected InnerElements()
        {
            this._elements = new ElementCollection();
        }

        public IList<IElementSerializable> Elements
        {
            get
            {
                return this._elements;
            }
        }

        public IElement this[string id]
        {
            get
            {
                if (null == id)
                {
                    throw new ArgumentNullException(id);
                }
                else if (0 == id.Length)
                {
                    throw new ArgumentOutOfRangeException(id);
                }

                IElement value = null;

                if (id == this.Id)
                {
                    value = this;
                }
                else
                {
                    value = this._elements[id].ToElement();
                }

                return value;
            }
        }

        public void Add(LabelledControl pair)
        {
            if (null == pair)
            {
                throw new ArgumentNullException("pair");
            }

            this.Elements.Add(pair.Label);
            this.Elements.Add(pair.Control);
        }

        public override void ReadXml(XmlReader reader)
        {
            base.ReadXml(reader);
            this._elements.ReadXml(reader);
        }

        public override void WriteXml(XmlWriter writer)
        {
            base.WriteXml(writer);

            writer.WriteRaw(this._elements.ToString());
        }
    }
}